package notice.buzz;


import com.jinyou.utils.common.*;
import com.jinyouapp.client.push.JPushClient;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import jPush.dao.JPushMessage;
import notice.dao.MainNotice;
import notice.dao.NoticeType;
import notice.dao.NoticeVO;
import notice.dao.UserNotice;
import o2o.business.image.ImageBusiness;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.MongoDaoImpl;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.user.UserInfo;
import o2o.system.Common;
import o2o.system.data.SYS_CONFIG_PATH;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * 消息处理
 * 版本v1.1
 * Jahnke  2017年1月11日 21:31:34
 */
public class NoticeBusiness {
    public static String noticeMainDB = "o2o_notice_main";
    public static String noticeUserDB = "o2o_notice_user";
    private static String noticeMainCol = "notice";

    public static String getNoticeMainDB(Long orgId) {
        return noticeMainDB;
    }

    public static String getNoticeMainColl(Long orgId) {
        if ((orgId == null) || (orgId.longValue() < 1L)) {
            return noticeMainCol;
        }
        return noticeMainCol + "_" + orgId;
    }

    public static String getNoticeUserDB(Long orgId) {
        return noticeUserDB;
    }

    public static String getUserColl(String username) {
        return username;
    }

    public static Long getOrgId(Long orgId) {
        if (orgId == null || orgId < 1L) {
            return 0l;
        }
        return orgId;
    }

    //保存消息
    public static void saveNotice(Long orgId, String fromUsername, Set<String> toUserNames, NoticeVO ntcvo) {
        orgId = getOrgId(orgId);
        long createTim = DateUtils.getCurrTime();

        MainNotice mntc = new MainNotice();
        String _id = ToolUtils.getNeedString(18);
        try {
            BeansUtils.bean2Bean(ntcvo, mntc, null);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        mntc.set_id(_id);
        mntc.setDelFlag(0);
        if (ValidateUtil.isNull(fromUsername)) {//无发送人 默认为系统发布
            fromUsername = "system";
        }
        mntc.setFromUsername(fromUsername);

        List<HashMap<String, Object>> images = new ArrayList<HashMap<String, Object>>();
        String filePath = Common.sdfMonth.format(new Date()) + "/";
//        String path = Common.proImgPath + Common.proNoticeImg + filePath;

        filePath = SYS_CONFIG_PATH.NOTICE_IMAGE + File.separator + filePath;
        String path = SYS_CONFIG_PATH.IMAGE_BASE_FILE + filePath;
//        String path = SYS_CONFIG_PATH.IMAGE_BASE_FILE + SYS_CONFIG_PATH.NOTICE_IMAGE + filePath;
        FileBusiness.isExitMkdir(path);
        HashMap<String, Object> image1 = dealNoticeImg(path, filePath, ntcvo.getFile1());
        HashMap<String, Object> image2 = dealNoticeImg(path, filePath, ntcvo.getFile2());
        HashMap<String, Object> image3 = dealNoticeImg(path, filePath, ntcvo.getFile3());
        HashMap<String, Object> image4 = dealNoticeImg(path, filePath, ntcvo.getFile4());
        HashMap<String, Object> image5 = dealNoticeImg(path, filePath, ntcvo.getFile5());
        HashMap<String, Object> image6 = dealNoticeImg(path, filePath, ntcvo.getFile6());

        if (image1 != null) {
            images.add(image1);
        }
        if (image2 != null) {
            images.add(image2);
        }
        if (image3 != null) {
            images.add(image3);
        }
        if (image4 != null) {
            images.add(image4);
        }
        if (image5 != null) {
            images.add(image5);
        }
        if (image6 != null) {
            images.add(image6);
        }
        mntc.setImages(images);
        mntc.setCreateTim(createTim);
        mntc.setOrgId(orgId);

        List rangeAll = new ArrayList();
        String sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
//        Set<String> shopUsernameList = new HashSet<>();
        for (String username : toUserNames) {
            HashMap rag = new HashMap();
            rag.put("isRead", 0);
            rag.put("isLike", 0);
            rag.put("username", username);
            rag.put("updateTime", createTim);
            rangeAll.add(rag);

            //只存用户表
            UserNotice un = new UserNotice();
            try {
                ObjectUtils.copyPropertiesExclude(mntc, un, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            un.setContent("您收到一条新的" + NoticeType.getTypeName(mntc.getType()) + (ValidateUtil.isNotNull(mntc.getTitle()) ? ":" + mntc.getContent() : ""));
            un.setForeignKey(_id);
            if (ntcvo.getSaveMain() != 1) {
                un.setImages(images);
                JMSNotify notify = JMSNotify.getInstance().setCreateTim(createTim).setType(JMSTypeContent.USERS_CURR_NOTICE).setReceivers(toUserNames);
                JmsSender.setTopicSender(notify);
            } else {
                un.setImages(images);
            }
            MongoDaoImpl.getInstance().insert(getNoticeUserDB(orgId), getUserColl(username), BeansUtils.beanToHashMap(un));        // 主表

        }
        if (ntcvo.getSaveMain() == 1) {
            mntc.setRangeAll(rangeAll);
            MongoDaoImpl.getInstance().insert(getNoticeMainDB(orgId), getNoticeMainColl(orgId), BeansUtils.beanToHashMap(mntc));        //主表
            try {
                JMSNotify notify = JMSNotify.getInstance().setCreateTim(createTim).setType(JMSTypeContent.USERS_CURR_NOTICE).setReceivers(toUserNames);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //极光推送
        try {
            if (orgId == 0) {
                JPushClient.getInstance().setSysCustomer(sysAppKey + "-" + JPushMessage.SHOP_OWNER).setPhones(toUserNames).setTitle(ntcvo.getTitle()).setContent(ntcvo.getContent()).pushByAlias();
                JPushClient.getInstance().setSysCustomer(sysAppKey + "-" + JPushMessage.USER).setPhones(toUserNames).setTitle(ntcvo.getTitle()).setContent(ntcvo.getContent()).pushByAlias();
                JPushClient.getInstance().setSysCustomer(sysAppKey + "-" + JPushMessage.POSTMAN).setPhones(toUserNames).setTitle(ntcvo.getTitle()).setContent(ntcvo.getContent()).pushByAlias();
            } else if (orgId == 1) {
                JPushClient.getInstance().setSysCustomer(sysAppKey + "-" + JPushMessage.SHOP_OWNER).setPhones(toUserNames).setTitle(ntcvo.getTitle()).setContent(ntcvo.getContent()).pushByAlias();
            } else if (orgId == 2) {
                JPushClient.getInstance().setSysCustomer(sysAppKey + "-" + JPushMessage.USER).setPhones(toUserNames).setTitle(ntcvo.getTitle()).setContent(ntcvo.getContent()).pushByAlias();
            } else if (orgId == 4) {
                JPushClient.getInstance().setSysCustomer(sysAppKey + "-" + JPushMessage.POSTMAN).setPhones(toUserNames).setTitle(ntcvo.getTitle()).setContent(ntcvo.getContent()).pushByAlias();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除消息
    public static void delNotice(Long orgId, String username, Map<String, Object> map) {
        orgId = getOrgId(orgId);

        MongoDaoImpl.getInstance().delete(getNoticeUserDB(orgId), getUserColl(username), map);
    }

    //删除主表消息
    public static void delMainNotice(Long orgId, String username, String noticeId) {
        orgId = getOrgId(orgId);

        BasicDBObject where = new BasicDBObject("_id", noticeId);

        BasicDBObject newValue = new BasicDBObject();
        newValue.append("$set", new BasicDBObject().append("delFlag", Integer.valueOf(0)));

        MongoDaoImpl.getInstance().update(getNoticeMainDB(orgId), getNoticeMainColl(orgId), where, newValue);
    }

    //个数
    public static long count(Long orgId, Map<String, Object> map) {
        orgId = getOrgId(orgId);
        return MongoDaoImpl.getInstance().count(getNoticeMainDB(orgId), getNoticeMainColl(orgId), map);
    }

    // 未读消息个数
    public static long unreadCount(Long orgId, String userName, Map<String, Object> map) {
        orgId = getOrgId(orgId);
        return MongoDaoImpl.getInstance().count(getNoticeUserDB(orgId), getUserColl(userName), map);
    }

    //获取用户的消息列表
    public static List<HashMap<String, Object>> list(Long orgId, String username, long createTim, int type, int size, int refreshType) {
        orgId = getOrgId(orgId);

        HashMap<String, Object> mapPara = new HashMap<String, Object>();
        mapPara.put("delFlag", 0);
        if (createTim == 0L) {
            mapPara.put("createTim", new BasicDBObject("$gt", createTim));
        } else if (createTim > 0L) {
            if (0 == refreshType - 1)
                mapPara.put("createTim", new BasicDBObject("$gt", createTim));
            else if (0 == refreshType - 2) {
                mapPara.put("createTim", new BasicDBObject("$lt", createTim));
            }
        }
        if (type >= 0) {
            mapPara.put("type", type);
        }

        List<HashMap<String, Object>> lista = MongoDaoImpl.getInstance().find(getNoticeUserDB(orgId), getUserColl(username), mapPara, size < 1 ? 20 : size, "createTim", -1);
        if (lista != null && lista.size() > 0) {
            lista = formatList(lista, null);

            return lista;
        }
        return null;
    }

    //获取系统消息列表
    public static List<HashMap<String, Object>> systemNoticeList(Long orgId, long createTim, int type, int size, int refreshType) {
        orgId = getOrgId(orgId);

        HashMap<String, Object> mapPara = new HashMap();

        if (createTim == 0L) {
            size = 40;
            mapPara.put("createTim", new BasicDBObject("$gt", Long.valueOf(createTim)));
        } else if (createTim > 0L) {
            if (0 == refreshType - 1)
                mapPara.put("createTim", new BasicDBObject("$gt", Long.valueOf(createTim)));
            else if (0 == refreshType - 2) {
                mapPara.put("createTim", new BasicDBObject("$lt", Long.valueOf(createTim)));
            }
        }
        mapPara.put("type", type);
        mapPara.put("delFlag", 0);
        List<HashMap<String, Object>> list = MongoDaoImpl.getInstance().find(getNoticeMainDB(orgId), getNoticeMainColl(orgId), mapPara, size, "createTim", -1);

        list = formatList(list, null);
        return list;
    }

    //获取小区的用户列表信息
    public static List<HashMap<String, Object>> communityList(Long orgId, long createTim, int type, int size, int refreshType) {
        orgId = getOrgId(orgId);

        HashMap<String, Object> mapPara = new HashMap();

        if (createTim == 0L) {
            size = 40;
            mapPara.put("createTim", new BasicDBObject("$gt", Long.valueOf(createTim)));
        } else if (createTim > 0L) {
            if (refreshType == 1)
                mapPara.put("createTim", new BasicDBObject("$gt", Long.valueOf(createTim)));
            else if (refreshType == 2) {
                mapPara.put("createTim", new BasicDBObject("$lt", Long.valueOf(createTim)));
            }
        }
        mapPara.put("type", type);
        mapPara.put("delFlag", 1);
        List<HashMap<String, Object>> list = MongoDaoImpl.getInstance().find(getNoticeMainDB(orgId), getNoticeMainColl(orgId), mapPara, size, "createTim", -1);

        list = formatList(list, null);
        return list;
    }


    public static HashMap<String, Object> get(Long orgId, String username, String id) {
        orgId = getOrgId(orgId);

        if (ValidateUtil.isNull(username)) {
            return null;
        }

        HashMap mapPara = new HashMap();
        mapPara.put("_id", id);
        List list = MongoDaoImpl.getInstance().find(getNoticeMainDB(orgId), getNoticeMainColl(orgId), mapPara, 1, "timestamped", -1);
        if ((list == null) || (list.size() < 1)) {
            return null;
        }

        return (HashMap) list.get(0);
    }

    //喜欢
    public static boolean like(Long orgId, String username, String id) {
        orgId = getOrgId(orgId);

        if (ValidateUtil.isNull(username)) {
            return false;
        }
        BasicDBObject where = new BasicDBObject().append("_id", id);

        DBObject value1 = new BasicDBObject();
        value1.put("isLike", Integer.valueOf(1));

        DBObject upValue = new BasicDBObject();
        upValue.put("$set", value1);

        MongoDaoImpl.getInstance().update(getNoticeMainDB(orgId), getNoticeMainColl(orgId), where, upValue);

        MongoDaoImpl.getInstance().update(getNoticeUserDB(orgId), getUserColl(username), where, upValue);

        return true;
    }

    //设为已读
    public static boolean readNotice(Long orgId, String username, String msgIds) {
        orgId = getOrgId(orgId);
        if (ValidateUtil.isNull(username)) {
            return false;
        }
        String[] noticeIds = msgIds.split(",");
        for (int i = 0; i < noticeIds.length; i++) {
            String id = noticeIds[i];
            BasicDBObject where = new BasicDBObject().append("_id", id);

            DBObject value1 = new BasicDBObject();
            value1.put("isRead", Integer.valueOf(1));

            DBObject upValue = new BasicDBObject();
            upValue.put("$set", value1);

            MongoDaoImpl.getInstance().update(getNoticeMainDB(orgId), getNoticeMainColl(orgId), where, upValue);

            MongoDaoImpl.getInstance().update(getNoticeUserDB(orgId), getUserColl(username), where, upValue);
        }
        return true;
    }

    // 删除某个时间前的消息
    public static void delNotice(Long time) {
        if (ValidateUtil.isNotAbsLong(time)) {
            // 没传的话，默认90天前
            time = DateUtils.getPreDaysOfTimestamp(90l);
        }

        HashMap<String, Object> mapPara = new HashMap<String, Object>();
        mapPara.put("createTim", new BasicDBObject("$lt", time));// 小于
//        mapPara.put("createTim", new BasicDBObject("$gt", createTim));// 大于
        mapPara.put("type", NoticeType.order);


        Long orgId = getOrgId(Long.parseLong(UserType.ALL + ""));
        Long orgId1 = getOrgId(Long.parseLong(UserType.SINGLE + ""));
        MongoDaoImpl.getInstance().delete(getNoticeMainDB(orgId), getNoticeMainColl(orgId), mapPara);
        MongoDaoImpl.getInstance().delete(getNoticeMainDB(orgId1), getNoticeMainColl(orgId1), mapPara);

        MongoDaoImpl.getInstance().delete(getNoticeUserDB(null), mapPara);
    }

    //-----------------------
    private static HashMap<String, Object> dealNoticeImg(String path, String filePath, MultipartFile file) {
        if (file == null) {
            return null;
        }
        String img = ToolUtils.getNeedString(17);
        String imgOrigal = img + "B.jpg";
        String imgNew = img + "C.jpg";
        try {
            File origalFile = new File(path + "//" + imgOrigal);
            file.transferTo(origalFile);

            File resizeFile = new File(path + "//" + imgNew);
            ImageBusiness.resize(origalFile, 460, -1, 0.6F, resizeFile);
            HashMap image = new HashMap();
            image.put("urlB", filePath + imgOrigal);
            image.put("url", filePath + imgNew);

            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //格式化消息结构
    private static List<HashMap<String, Object>> formatList(List<HashMap<String, Object>> list, HashMap<String, HashMap<String, Object>> fromMap) {
        if (list == null || list.size() < 1) {
            return list;
        }
        //格式化消息
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("id", (list.get(i)).get("_id").toString());
            list.get(i).put("typeName", NoticeType.getTypeName(Integer.parseInt(list.get(i).get("type").toString())));

            //发布者帐号信息
            String fromUsername = list.get(i).get("fromUsername").toString();
            if (fromUsername.equals("system")) {
                list.get(i).put("fromUser", "system");
                list.get(i).put("fromUserImage", "");
            } else {
                UserInfo info = UserInfoMemory.getInstance().getUserInfo(fromUsername);
                list.get(i).put("fromUser", info != null ? info.getName() : "");
                if (ValidateUtil.isNotNull(info.getSignPhoto())) {
                    if (ValidateUtil.isNotNetUrl(info.getSignPhoto())) {
//                        list.get(i).put("fromUserImage", Common.imageUrl + info.getSignPhoto());
                        list.get(i).put("fromUserImage", SYS_CONFIG_PATH.IMAGE_BASE_URL + info.getSignPhoto());
                    }
                } else {
                    list.get(i).put("fromUserImage", "");
                }

            }

            list.get(i).put("contentId", list.get(i).get("_id").toString());
            list.get(i).put("contentType", Integer.valueOf(Integer.parseInt(list.get(i).get("type").toString())));

            HashMap<String, Object> fromData = (fromMap != null ? fromMap.get(list.get(i).get("_id").toString()) : null);

            list.get(i).put("isRead", fromData == null ? (list.get(i).containsKey("isRead") ? list.get(i).get("isRead") : Integer.valueOf(0)) : fromData.containsKey("isRead") ? fromData.get("isRead") : Integer.valueOf(0));
            list.get(i).put("isLike", fromData == null ? (list.get(i).containsKey("isLike") ? list.get(i).get("isLike") : Integer.valueOf(0)) : fromData.containsKey("isLike") ? fromData.get("isLike") : Integer.valueOf(0));

            List<HashMap<String, Object>> imageList = list.get(i).get("images") != null ? JsonUtils.jsonToListmap(list.get(i).get("images").toString()) : null;

            List<HashMap<String, Object>> images = new ArrayList<HashMap<String, Object>>();
            if (imageList != null && imageList.size() > 0) {
                for (int m = 0; m < imageList.size(); m++) {
                    HashMap<String, Object> image = new HashMap<String, Object>();
//                    image.put("url", Common.imageUrl + imageList.get(m).get("url").toString());
//                    image.put("urlB", Common.imageUrl + imageList.get(m).get("urlB").toString());
                    image.put("url", SYS_CONFIG_PATH.IMAGE_BASE_URL + imageList.get(m).get("url").toString());
                    image.put("urlB", SYS_CONFIG_PATH.IMAGE_BASE_URL + imageList.get(m).get("urlB").toString());
                    images.add(image);
                }
                list.get(i).put("images", images);
            }

            list.get(i).remove("rangeAll");
        }

        return list;
    }
}

